import { reactive } from 'vue'
import type { DesignerState, FormSchema, FormField, DataSource, MaterialItem } from '@/types'

export const store = reactive<DesignerState>({
  currentForm: {
    fields: [],
    layout: {},
    rules: {}
  },
  selectedField: null,
  dataSources: [],
  materials: [],
  dragMaterial: null // 添加拖拽物料状态
})

export const useDesignerStore = () => {
  const addField = (field: FormField) => {
    store.currentForm.fields.push(field)
    store.selectedField = field
  }

  const updateField = (fieldId: string, updates: Partial<FormField>) => {
    const field = store.currentForm.fields.find(f => f.id === fieldId)
    if (field) {
      Object.assign(field, updates)
      store.selectedField = field
    }
  }

  const removeField = (fieldId: string) => {
    const index = store.currentForm.fields.findIndex(f => f.id === fieldId)
    if (index > -1) {
      store.currentForm.fields.splice(index, 1)
      if (store.selectedField?.id === fieldId) {
        store.selectedField = null
      }
    }
  }

  const selectField = (field: FormField | null) => {
    store.selectedField = field
  }

  const exportSchema = (): FormSchema => {
    return JSON.parse(JSON.stringify(store.currentForm))
  }

  const importSchema = (schema: FormSchema) => {
    store.currentForm = schema
    store.selectedField = null
  }

  const addDataSource = (dataSource: DataSource) => {
    store.dataSources.push(dataSource)
  }

  const registerMaterial = (material: MaterialItem) => {
    store.materials.push(material)
  }

  return {
    store,
    addField,
    updateField,
    removeField,
    selectField,
    exportSchema,
    importSchema,
    addDataSource,
    registerMaterial
  }
}